<?php

namespace App;


class Utils
{
    const SOURCE_STRING = '6NQK58SGVXU7ECBPL4M2FZA39DTHYR';

    public static function invite_encode(int $phone): string
    {
        $num = $phone;

        $code = '';

        while ($num > 0) {
            $mod = $num % 30;
            $num = ($num - $mod) / 30;
            $code = self::SOURCE_STRING[$mod] . $code;
        }

        if (empty($code[3])) {
            $code = str_pad($code, 4, '0', STR_PAD_LEFT);
        }

        return $code;
    }

    public static function invite_decode(string $code): int
    {
        if (strrpos($code, '0') !== false) {
            $code = substr($code, strrpos($code, '0')+1);
        }

        $len = strlen($code);
        $code = strrev($code);
        $num = 0;
        for ($i=0; $i < $len; $i++) {
            $num += strpos(self::SOURCE_STRING, $code[$i]) * pow(30, $i);
        }

        return $num;
    }
}
